package ru.evstpet.kubejob.repository;

import java.util.List;

import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Repository;

import lombok.RequiredArgsConstructor;
import ru.evstpet.kubejob.entity.Person;

@RequiredArgsConstructor
@Repository
public class PersonRepository {

    private final JdbcClient client;

    public List<Person> getAll() {
        String sql = """
                      select id, firstname, lastname, username from person
                """;

        return client.sql(sql)
                .query(Person.class)
                .list();
    }

    public Person get(Long id) {
        String sql = """
                      select id, firstname, lastname, username from person where id = ?
                """;

        return client.sql(sql)
                .param(id)
                .query(Person.class)
                .single();
    }

    public Person create(Person person) {
        String sql = """
                      insert into person (firstname, lastname, username)
                      values (:firstName, :lastName, :userName)
                """;

        var gkh = new GeneratedKeyHolder();

        client.sql(sql)
                .paramSource(person)
                .update(gkh);

        return client.sql("select id, firstname, lastname, username from person where id = ?")
                .param(gkh.getKeys().get("id"))
                .query(Person.class)
                .single();

    }

    public Person update(Person person) {
        String sql = """
                      update person set firstname = :firstName, lastname = :lastName, username = :userName
                      where id = ?
                """;

        client.sql(sql)
                .paramSource(person)
                .update();

        return client.sql("select id, firstname, lastname, username from person where id = :id")
                .param(person.getId())
                .query(Person.class)
                .single();

    }

    public void delete(Long id) {
        var sql = """
                delete from person where id = :id
                """;
        client.sql(sql)
                .param("id", id)
                .update();
    }

}
